package com.Sep_Twenty_Seven;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 47. 全排列 II
 * 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 *https://leetcode.cn/problems/permutations-ii/
 *
 * 2022/09/27 17:12
 */

public class Solution47 {

    List<List<Integer>> list=new ArrayList<>();
    List<Integer> path=new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        boolean[] used=new boolean[nums.length];
        Arrays.fill(used,false);
        Arrays.sort(nums);
        backtracking(nums,used);
        return list;
    }

    public void backtracking(int[] nums,boolean[] used){
        if (path.size()== nums.length)
        {
            list.add(new ArrayList<>(path));
            return;
        }
        for (int i=0;i<nums.length;i++)
        {
            if ((i>0&&nums[i]==nums[i-1]&&!used[i-1])) continue;
            if (used[i]) continue;
            used[i]=true;
            path.add(nums[i]);
            backtracking(nums,used);
            path.remove(path.size()-1);
            used[i]=false;
        }
    }

    public static void main(String[] args) {
        Solution47 solution47=new Solution47();
        int[] nums={1,1,2};
        System.out.println(solution47.permuteUnique(nums));
    }

}
